//
//  Taobao.m
//  ShoppingCompare
//
//  Created by Wenjie on 11-5-15.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "Taobao.h"
#import "RootViewController.h"
#import <CommonCrypto/CommonDigest.h>
#import "ItemList.h"
#import "LKGoogleTranslator.h"


@implementation Taobao


+ (NSString *)md5:(NSString *)str {
	const char *cStr = [str UTF8String];
	unsigned char result[32];
	CC_MD5( cStr, strlen(cStr), result );
	return [NSString stringWithFormat:
			@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
			result[0], result[1], result[2], result[3], 
			result[4], result[5], result[6], result[7],
			result[8], result[9], result[10], result[11],
			result[12], result[13], result[14], result[15]
			]; 
}

+ (NSString *) setParameters:(NSMutableDictionary *) parameters andSecret:(NSString *) secret {
	NSArray* myKeys = [parameters allKeys];
	NSArray* sortedKeys = [myKeys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
	int j = [parameters count];
	
	NSString* query = [[[NSString alloc] initWithString:secret] autorelease];
	for (int i = 0; i < j; i++) {
		query = [query stringByAppendingString:[sortedKeys objectAtIndex:i]];
		query = [query stringByAppendingString:[parameters objectForKey:[sortedKeys objectAtIndex:i]]];
	}
	query = [query stringByAppendingString:secret];
	return [Taobao md5:query];
}

+ (NSString *) setParameters:(NSMutableDictionary *) parameters {
	NSString* postData = @"";
	BOOL hasParam = NO;
	for (NSString *perKey in parameters) {
		if (hasParam) {
			postData = [postData stringByAppendingString:@"&"];
		}
		postData = [postData stringByAppendingString:perKey];
		postData = [postData stringByAppendingString:@"="];
		postData = [postData stringByAppendingString:[parameters objectForKey:perKey]];
		hasParam = YES;
	}
	return postData;
}


+(NSData*) getResult:(long)page {
	NSMutableDictionary* parameters = [[NSMutableDictionary alloc] init];
	[parameters setObject:@"xml" forKey:@"format"];
	[parameters setObject:@"taobao.items.get" forKey:@"method"];
	[parameters setObject:@"md5" forKey:@"sign_method"];
	[parameters setObject:taobaoKey forKey:@"app_key"];
	[parameters	setObject:@"10" forKey:@"page_size"];
	
	// ----------- need control ----------------
	[parameters setObject:[NSString stringWithFormat: @"%d", page] forKey:@"page_no"];
	
	[parameters	setObject:@"2.0" forKey:@"v"];
	
	NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString* locationString = [formatter stringFromDate:[NSDate date]];
	[parameters setObject:locationString forKey:@"timestamp"];
	[formatter release];
	[locationString release];
	
	[parameters setObject:@"num_iid, title, nick, pic_url, cid, price, type, delist_time, post_fee" forKey:@"fields"];
	if (key.length > 0) {
		[parameters setObject:key forKey:@"q"];
	}
	

	if (minP > -1)
		[parameters	setObject:[NSString stringWithFormat:@"%d", minP] forKey:@"start_price"];
	if (maxP > -1) 
		[parameters setObject:[NSString stringWithFormat:@"%d", maxP] forKey:@"end_price"];
	if (order > 0) 
		if (order == 1) [parameters setObject:@"price:asc" forKey:@"order_by"];
		else [parameters setObject:@"price:desc" forKey:@"order_by"];

	
	[parameters setObject:[Taobao setParameters:parameters andSecret:taobaoSecret] forKey:@"sign"];
	
	NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] init] autorelease];
	[request setURL:[NSURL URLWithString:taobaoURL]];
	[request setHTTPMethod:@"POST"];
	[request setTimeoutInterval:300];
	NSString *contentType = [NSString stringWithFormat:@"application/x-www-form-urlencoded;charset=utf-8"]; 
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"]; 
	
	NSMutableData* postData = [NSMutableData data];
	[postData appendData:[[Taobao setParameters:parameters] dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
	[request setHTTPBody: postData];
	
	NSHTTPURLResponse* urlResponse = nil;   
    NSError* error = [[[NSError alloc] init] autorelease];   
    NSData* responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
	
	return responseData;
}

+ (NSString*)toUTF8:(NSString *)encodeStr {
    NSString *preprocessedString = (NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, (CFStringRef)encodeStr, CFSTR(""), kCFStringEncodingUTF8);

    NSString *resultStr = [(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)preprocessedString, nil, nil, kCFStringEncodingUTF8) autorelease];  

    return resultStr;
}

+ (NSData *) getResultFromKakaku:(long)page {

	NSMutableDictionary* parameters = [[NSMutableDictionary alloc] init];
	
	[parameters setObject:@"b0feed96f32dc8ee76e543d5d818ab3e" forKey:@"ApiKey"];
	

	if (key.length > 0) {	
		[parameters setObject:[Taobao toUTF8: key] forKey:@"Keyword"];
	}
	[parameters setObject:@"10" forKey:@"HitNum"];
	[parameters setObject:@"utf8" forKey:@"Charset"];
	[parameters setObject:[NSString stringWithFormat: @"%d", page] forKey:@"pageNum"];
	
	if (minP > -1)
		[parameters	setObject:[NSString stringWithFormat:@"%d", minP] forKey:@"MinPrice"];
	if (maxP > -1) 
		[parameters setObject:[NSString stringWithFormat:@"%d", maxP] forKey:@"MaxPrice"];
	if (order > 0) 
		if (order == 1) [parameters setObject:@"pricerank" forKey:@"SortOrder"];
		else [parameters setObject:@"-pricerank" forKey:@"SortOrder"];
	
	NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"http://api.kakaku.com/WebAPI/ItemSearch/Ver1.0/ItemSearch.aspx?%@", [Taobao setParameters:parameters]]];

	NSError *error;
	NSString *responseString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
	return [responseString dataUsingEncoding:NSUTF8StringEncoding];
}

+ (void) showSearchResult:(long) page_no {	
	pageNo = page_no;
	if (inTaobao) {
		resultData = [Taobao getResult: pageNo];
	} else {
		resultData = [Taobao getResultFromKakaku: pageNo];
	}
	
}

@end